package com.chinatelecom.ifree.business.dao.order.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chinatelecom.ifree.business.dao.base.DbcpPool;

public abstract class BaseDaoSupport<T> {
	private static transient Logger logger = LoggerFactory.getLogger(BaseDaoSupport.class);
	protected String sql;

	public void saveEntity(T t) throws Exception {
		Connection conn = null;
		PreparedStatement statement = null;
		try {
			conn = DbcpPool.getInstance().getConn();
			statement = conn.prepareStatement(sql);
			executeSql(statement, t);
			statement.execute();
		} catch (Exception e) {
			logger.error("saveEntity", e);
			throw e;
		} finally {
			DbcpPool.getInstance().closeConnection(statement, conn);
		}
	}

	public void saveBatchEntity(T[] t) throws Exception {
		Connection conn = null;
		PreparedStatement statement = null;
		try {
			conn = DbcpPool.getInstance().getConn();
			conn.setAutoCommit(false);
			statement = conn.prepareStatement(sql);
			executeBatchSql(statement, t);
			statement.executeBatch();
			conn.commit();
		} catch (Exception e) {
			logger.error("saveBatchEntity", e);
			throw e;
		} finally {
			DbcpPool.getInstance().closeConnection(statement, conn);
		}
	}

	public T getEntityByPK(String obj) throws Exception {
		Connection conn = null;
		PreparedStatement statement = null;
		ResultSet rs = null;
		try {
			conn = DbcpPool.getInstance().getConn();
			statement = conn.prepareStatement(sql);
			statement.setString(1, obj);
			rs = statement.executeQuery();
			return executeSingleResultSet(rs);
		} catch (Exception e) {
			logger.error("getEntityByPK", e);
			throw e;
		} finally {
			DbcpPool.getInstance().closeConnection(rs, statement, conn);
		}
	}

	public void updateEntity(String pk, int obj) throws Exception {
		Connection conn = null;
		PreparedStatement statement = null;
		try {
			conn = DbcpPool.getInstance().getConn();
			statement = conn.prepareStatement(sql);
			statement.setInt(1, obj);
			statement.setString(2, pk);
			statement.executeUpdate();
		} catch (Exception e) {
			logger.error("updateEntity", e);
			throw e;
		} finally {
			DbcpPool.getInstance().closeConnection(statement, conn);
		}
	}

	public abstract T executeSingleResultSet(ResultSet rs) throws Exception;

	public abstract void executeSql(PreparedStatement state, T t) throws Exception;

	public abstract void executeBatchSql(PreparedStatement state, T[] t) throws Exception;
}
